package com.yzcrm.erp.crm.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Aop;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yzcrm.common.config.paragetter.BasePageRequest;
import com.yzcrm.common.constant.BaseConstant;
import com.yzcrm.erp.admin.entity.AdminField;
import com.yzcrm.erp.admin.entity.AdminFieldv;
import com.yzcrm.erp.admin.entity.AdminFile;
import com.yzcrm.erp.admin.entity.AdminRecord;
import com.yzcrm.erp.admin.service.AdminExamineRecordService;
import com.yzcrm.erp.admin.service.AdminFieldService;
import com.yzcrm.erp.admin.service.AdminFileService;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.crm.common.CrmParamValid;
import com.yzcrm.erp.crm.entity.CrmActionRecord;
import com.yzcrm.erp.crm.entity.CrmContract;
import com.yzcrm.erp.crm.entity.CrmCustomer;
import com.yzcrm.erp.crm.entity.CrmLeads;
import com.yzcrm.erp.oa.entity.OaEvent;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.FieldUtil;
import com.yzcrm.utils.R;

import java.util.*;
import java.util.stream.Collectors;

public class CrmLeadsService {
    @Inject
    private AdminFieldService adminFieldService;

    @Inject
    private FieldUtil fieldUtil;

    @Inject
    private CrmRecordService crmRecordService;

    @Inject
    private AdminFileService adminFileService;

    @Inject
    private CrmParamValid crmParamValid;

    @Inject
    private AdminExamineRecordService examineRecordService;
    
    @Inject
    private CrmCustomerService crmCustomerService;
    /**
     * @author wyq
     * 分页条件查询线索
     */
    public Page<Record> getLeadsPageList(BasePageRequest<CrmLeads> basePageRequest) {
        String leadsName = basePageRequest.getData().getLeadsName();
        if (!crmParamValid.isValid(leadsName)){
            return new Page<>();
        }
        String telephone = basePageRequest.getData().getTelephone();
        String mobile = basePageRequest.getData().getMobile();
        if (StrUtil.isEmpty(leadsName) && StrUtil.isEmpty(telephone) && StrUtil.isEmpty(mobile)){
            return new Page<>();
        }
        return Db.paginate(basePageRequest.getPage(), basePageRequest.getLimit(), Db.getSqlPara("crm.leads.getLeadsPageList",Kv.by("leadsName",leadsName).set("telephone",telephone).set("mobile",mobile)));
    }

    /**
     * @author lg
     * 新增或更新线索
     */
    @Before(Tx.class)
    public R addOrUpdate(JSONObject object) {
        CrmLeads crmLeads = object.getObject("entity", CrmLeads.class);
        String batchId = StrUtil.isNotEmpty(crmLeads.getBatchId()) ? crmLeads.getBatchId() : IdUtil.simpleUUID();
        crmRecordService.updateRecord(object.getJSONArray("field"), batchId);
        adminFieldService.save(object.getJSONArray("field"), batchId);
        if (crmLeads.getLeadsId() != null) {
             CrmLeads leads = new CrmLeads().dao().findById(crmLeads.getLeadsId());
             if (leads.getCheckStatus() != 4 && leads.getCheckStatus() != 2 && leads.getCheckStatus() != 5) {
                 return R.error("不能编辑，请先撤回再编辑！");
             }

             Map<String, Integer> map = examineRecordService.saveExamineRecord(3, object.getLong("checkUserId"), leads.getOwnerUserId(),
            		 leads.getExamineRecordId(), crmLeads.getCheckStatus());
             if (map.get("status") == 0) {
                 return R.error("没有启动的审核步骤，不能添加！");
             } else {
            	 crmLeads.setExamineRecordId(map.get("id"));
             }
             if (crmLeads.getCheckStatus() != null && crmLeads.getCheckStatus() == 5) {
            	 crmLeads.setCheckStatus(5);
             } else {
            	 crmLeads.setCheckStatus(0);
             }

            crmLeads.setCustomerId(0);
            crmLeads.setUpdateTime(DateUtil.date());
            
            crmRecordService.updateRecord(new CrmLeads().dao().findById(crmLeads.getLeadsId()), crmLeads, CrmEnum.CRM_LEADS);
            return crmLeads.update() ? R.ok() : R.error();
        } else {
            crmLeads.setCreateTime(DateUtil.date());
            crmLeads.setUpdateTime(DateUtil.date());
            crmLeads.setCreateUserId(BaseUtil.getUser().getUserId());
            if (crmLeads.getOwnerUserId() == null) {
                crmLeads.setOwnerUserId(BaseUtil.getUser().getUserId());
            }
            crmLeads.setBatchId(batchId);
            Map<String, Integer> map = examineRecordService.saveExamineRecord(3, object.getLong("checkUserId"), crmLeads.getOwnerUserId(), null, crmLeads.getCheckStatus());
            if (map.get("status") == 0) {
                return R.error("没有启动的审核步骤，不能添加！");
            } else {
            	crmLeads.setExamineRecordId(map.get("id"));
            }
            if (crmLeads.getCheckStatus() != null && crmLeads.getCheckStatus() == 5) {
            	crmLeads.setCheckStatus(5);
            } else {
            	crmLeads.setCheckStatus(0);
            }
            boolean save = crmLeads.save();
            crmRecordService.addRecord(crmLeads.getLeadsId(), CrmEnum.CRM_LEADS);
            return save ? R.ok() : R.error();
        }
    }

    /**
     * @author wyq
     * 基本信息
     */
    public List<Record> information(Integer leadsId) {
        Record record = queryById(leadsId);
        List<String> keyList = Arrays.asList("leads_name", "mobile", "address","telephone","next_time","remark");
        List<Record> recordList = adminFieldService.queryInformation(CrmEnum.CRM_LEADS,record, keyList);
        return recordList.stream().sorted(Comparator.comparingInt(r->-r.getInt("field_type"))).map(r-> r.remove("field_type","field_name","setting","type")).collect(Collectors.toList());
    }

    /**
     * @author wyq
     * 根据线索id查询
     */
    public Record queryById(Integer leadsId) {
        Record record = Db.findFirst(Db.getSql("crm.leads.queryById"), leadsId);
        List<Record> recordList = Db.find("select name,value from `yzcrm_admin_fieldv` where batch_id = ?", record.getStr("batch_id"));
        recordList.forEach(field->record.set(field.getStr("name"),field.getStr("value")));
        return record;
    }

    /**
     * @author wyq
     * 根据线索名称查询
     */
    public Record queryByName(String name) {
        return Db.findFirst(Db.getSql("crm.leads.queryByName"), name);
    }

    /**
     * @author wyq
     * 根据id 删除线索
     */
    public R deleteByIds(String leadsIds) {
        String[] idsArr = leadsIds.split(",");
        List<Record> idsList = new ArrayList<>();
        for (String id : idsArr) {
            Record record = new Record();
            idsList.add(record.set("leads_id", Integer.valueOf(id)));
        }
        List<Record> batchIdList = Db.find(Db.getSqlPara("crm.leads.queryBatchIdByIds",Kv.by("ids",idsArr)));
        return Db.tx(() -> {
            Db.batch(Db.getSql("crm.leads.deleteByIds"), "leads_id", idsList, 100);
            Db.batch("delete from yzcrm_admin_fieldv where batch_id = ?","batch_id",batchIdList,100);
            return true;
        }) ? R.ok() : R.error();
    }

    /**
     * @author wyq
     * 变更负责人
     */
    public R updateOwnerUserId(String leadsIds, Long ownerUserId) {
        String[] ids = leadsIds.split(",");
        int update = Db.update(Db.getSqlPara("crm.leads.updateOwnerUserId", Kv.by("ownerUserId", ownerUserId).set("ids", ids)));
        for (String id : ids) {
            crmRecordService.addConversionRecord(Integer.valueOf(id), CrmEnum.CRM_LEADS, ownerUserId);
        }
        return update > 0 ? R.ok() : R.error();
    }

    /**
     * @author lg
     * 潜在客户转目标客户
     */
    @Before(Tx.class)
    public R translate(String leadsIds,Long customerOwnerId,Integer customer_type) {
        String[] customerIdsArr = leadsIds.split(",");
        if(customerIdsArr.length > 0) {
        	Db.update(Db.getSqlPara("crm.customer.transform", Kv.by("customerIds", customerIdsArr).set("ownerUserId",customerOwnerId).set("customer_type",customer_type)));
        }
        
        for (String customerId : customerIdsArr) {
        	CrmCustomer crmCustomer = CrmCustomer.dao.findById(customerId);
        	if(customer_type == 1) {
        		//客户转潜在客户
        		crmRecordService.addConversionCustomerRecord(crmCustomer.getCustomerId(), CrmEnum.CRM_LEADS.getType(), crmCustomer.getCustomerName());
        	}else {
        		//客户转目标客户
        		crmRecordService.addConversionCustomerRecord(crmCustomer.getCustomerId(), CrmEnum.CRM_CUSTOMER.getType(), crmCustomer.getCustomerName());
        	}
        	
        }
        return R.ok();
    }

    /**
     * @author wyq
     * 查询编辑字段
     */
    public List<Record> queryField(Integer leadsId) {
        Record leads = queryById(leadsId);
        return adminFieldService.queryUpdateField(CrmEnum.CRM_LEADS.getType(),leads);
    }

    /**
     * @author wyq
     * 添加跟进记录
     */
    @Before(Tx.class)
    public R addRecord(AdminRecord adminRecord) {
        adminRecord.setCreateUserId(BaseUtil.getUser().getUserId());
        adminRecord.setCreateTime(DateUtil.date());
        adminRecord.setTypes("crm_leads");
        if (StrUtil.isEmpty(adminRecord.getCategory())){
            return R.error("跟进类型不能为空");
        }
        if (1 == adminRecord.getIsEvent()) {
            OaEvent oaEvent = new OaEvent();
            oaEvent.setTitle(adminRecord.getContent());
            oaEvent.setCreateUserId(adminRecord.getCreateUserId());
            oaEvent.setStartTime(adminRecord.getNextTime());
            oaEvent.setEndTime(DateUtil.offsetDay(adminRecord.getNextTime(), 1));
            oaEvent.setCreateTime(DateUtil.date());
            oaEvent.save();
        }
        CrmLeads crmLeads = new CrmLeads();
        crmLeads.setLastContent(adminRecord.getContent());
        crmLeads.setLeadsId(adminRecord.getTypesId());
        crmLeads.setFollowup(1);
        crmLeads.setNextTime(adminRecord.getNextTime());
        crmLeads.update();
        return adminRecord.save() ? R.ok() : R.error();
    }

    /**
     * @author wyq
     * 查看跟进记录
     */
    public List<Record> getRecord(BasePageRequest<CrmLeads> basePageRequest) {
        CrmLeads crmLeads = basePageRequest.getData();
        List<Record> recordList = Db.find(Db.getSql("crm.leads.getRecord"), crmLeads.getLeadsId());
        recordList.forEach(record -> {
            adminFileService.queryByBatchId(record.getStr("batch_id"), record);
        });
        return recordList;
    }


    /**
     * @author wyq
     * 获取线索导入查重字段
     */
    public R getCheckingField(){
        return R.ok().put("data","线索名称");
    }
}
